package cn.jkgly.wxUser.controller;

import cn.jkgly.accessToken.entity.AccessToken;
import cn.jkgly.accessToken.service.IAccessTokenService;
import cn.jkgly.utils.AuthUtil;
import cn.jkgly.utils.Https;
import cn.jkgly.utils.Sign;
import cn.jkgly.websocket.server.SocketServer;
import cn.jkgly.wxUser.entity.Result;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

@Controller
public class WxAuthController {
    private static final Logger logger = LoggerFactory.getLogger(SocketServer.class);
    @Autowired
    IAccessTokenService iAccessTokenService;
    @GetMapping("/auth/getCode")
    @ResponseBody
    protected void getCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // String backUrl = "http://auth.jkgly.cn/auth/getOpenid";
        String backUrl = "http://auth.jkgly.cn/auth/miniProgram/getOpenid";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize" + "?appid=" + AuthUtil.APPID + "&redirect_uri=" + URLEncoder.encode(backUrl) + "&response_type=code" +//固定code
                "&scope=snsapi_userinfo" +//snsapi_base(只返回openid),snsapi_userinfo
                "&state=state" +//用户自定义
                "#wechat_redirect";//锚点
        resp.sendRedirect(url);
    }

    /**
     * 微信小程序获取openid接口
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/auth/miniProgram/getOpenid")
    @ResponseBody
    protected Result<?> doGetMiniProgramGetOpenid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
       //小程序获取openid地址
        String url ="https://api.weixin.qq.com/sns/jscode2session?appid=wxc7b27c74a843fb97&secret=b3b63f00cd5c1388b4424fe52244189b&js_code="+code+"&grant_type=authorization_code";
        JSONObject jsonObject = AuthUtil.doGetJson(url);
        return Result.ok(jsonObject);
    }

    /**
     * 微信公众号获取openid及用户基本信息
     * @param req
     * @param resp
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/auth/officialAccounts/getOpenid")
    @ResponseBody
    protected Result<?> doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
        //公众号获取openid地址
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" + "?appid=" + AuthUtil.APPID + "&secret=" + AuthUtil.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
       JSONObject jsonObject = AuthUtil.doGetJson(url);
        System.out.println(jsonObject);
        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("access_token");

//        String tokenRefreshUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token" +
//                "?appid=APPID" +
//                "&grant_type=refresh_token" +
//                "&refresh_token=REFRESH_TOKEN";

        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" + "?access_token=" + token + "&openid=" + openid + "&lang=zh_CN";
        JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
        System.out.println(userInfo);
        return Result.ok(userInfo);
//        System.out.println(userInfo);
    }

    @GetMapping("/auth/getWXConfigSignature")
    @ResponseBody
    public Map getWXConfigSignature(@RequestParam(name = "url", required = true)  String url) {
        String wxJsapiTicket = getWXJsapiTicket();
        Map<String, String> ret = Sign.sign(wxJsapiTicket, url);
        ret.put("appId","wx3a06c113295b44c3");
        logger.info(">>>>>>"+ret.toString());
        return ret;
    }

    public String getWXJsapiTicket() {

        String access_token = getWXaccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
        String ticket = null;
        try {
            String tickets = Https.https(url, "GET");
            logger.info(tickets);
          //  int errcode = JSONObject.parseObject(tickets).getIntValue("errcode");

            ticket = JSONObject.parseObject(tickets).getString("ticket");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ticket;
    }
    private String getWXaccessToken() {
        String token = null;
        Date end = new Date();
        QueryWrapper<AccessToken> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("accountname","健康管理云").eq("username","admin");
        AccessToken accessToken =iAccessTokenService.getOne(queryWrapper);
        java.util.Date start = new java.util.Date(accessToken.getAddtoekntime().getTime());
        if ((end.getTime() - start.getTime()) / 1000 / 3600 >= 1.5) {
            String appid = AuthUtil.APPID;
            String secret = AuthUtil.APPSECRET;;
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            try {
                token = Https.https(url, "GET");
                token= JSONObject.parseObject(token).getString("access_token");
                accessToken.setAccountaccesstoken(token);
                accessToken.setAddtoekntime(new Date());
                iAccessTokenService.updateById(accessToken);
                logger.info(token);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            token=accessToken.getAccountaccesstoken();
        }

        return token;
    }
}


